#!/usr/bin/perl
#########################################################################
# NAME: admin.cgi
# DESC: 
# HIST:
#       16mar2008  GJ  ORIGINAL VERSION
#


use meterDB;
use CGI qw/:standard/;
use strict;

my $dbh = meterDB->new();

my $query = CGI->new();

print $query->header('text/html');

print <<EOF;
<html>
<head>
<title>Meters Database Administration</title>
<LINK REL=stylesheet HREF="property.css" TYPE="text/css">
<meta http-equiv="pragma" content="no-cache">
</head>
<body bgcolor=white fgcolor=black>
EOF

if (param('m') eq 'meter')
{
    meter_list() if (param('sm') eq 'list');
    meter_form() if (param('sm') eq 'form');
    meter_add() if (param('sm') eq 'add');
    meter_add() if (param('sm') eq 'update');
    meter_delete() if (param('sm') eq 'delete');
    meter_edit() if (param('sm') eq 'edit');
}
elsif (param('m') eq 'daemon')
{
    stop_daemon() if (param('sm') eq 'stop');
    start_daemon() if (param('sm') eq 'start');
}
elsif (param('m') eq 'system')
{
    system_upgrade() if (param('sm') eq 'upgrade');
}
else
{
    admin_menu();
}

print <<EOF;
</body>
</html>
EOF




#############################################################################
# NAME: admin_menu
# DESC: presents a simple menu of administrative tasks and a summary of current
#        system status.
# HIST: 19mar2008  GJ ORIGINAL VERSION
sub admin_menu
{
    use Filesys::Df;
    my ($ref) = df("/");
 
    my ($metermon);

    open(PS, "ps | grep /usr/bin/metermon | grep -v grep | cut -d ' ' -f 2 | ");
    my ($metermonpid) = <PS>;
    close(PS);


    if ( $metermonpid eq "" ) {
	$metermon = "****STOPPED*****";
    } else {
	$metermon = "RUNNING - PID=$metermonpid";
    }


    print ('<h1 MeterServ Administration</h1>',
	   '<h2>System Status</h2>',
	   '<table border=1>',
	   '<tr><td>Disk Usage [%full]</td>',
	      '<td>',$ref->{per},'%</td></tr>',
	   '<tr><td>Metermon Daemon</td>',
	      '<td>',$metermon,'</td></tr>',
	   '</table>');

    print ('<h2>Admin Options</h2>',
	   '<ol>',
	   '<li><a href="/cgi-bin/admin.cgi?m=meter&sm=list">Configure Meters</a></li>',
	   '<li><a href="/cgi-bin/admin.cgi?m=daemon&sm=stop">Stop Metermon Daemon</a></li>',
	   '<li><a href="/cgi-bin/admin.cgi?m=daemon&sm=start">Start Metermon Daemon</a></li>',
	   '<li><a href="/cgi-bin/admin.cgi?m=system&sm=upgrade">System Upgrade</a></li>',
	   '</ol>');
}






##############################################################################
# NAME: meter_list
# DESC: presents a list of all meters as a table.  Includes liks to the
#        forms to edit the meter details.
# HIST: 19mar2008  GJ  ORGINAL VERSION
#
sub meter_list
{
    my $meters = $dbh->get_generic_sql('meters','id','select * from meters');
    my $datacount = scalar keys %{$meters};
    print <<EOF;
<h2>Meter Configuration</h2>
<p class=pageheader>Select meter to edit
 or <a href="admin.cgi?m=meter&sm=form">Add a New Meter</a>.  Delete a meter 
 using the checkboxes below.</p>
<form method=POST action=admin.cgi>
<input type=hidden name=m value=meter>
<input type=hidden name=sm value=delete>
EOF

    print('<table border=0 cellpadding=0 cellspacing=0>',
          '<tr><th align=left>ID</th><th width=15>&nbsp;</th>',
          '<th align=left>Description</th><th width=15>&nbsp;</th>',
          '<th align=left>Input No.</th><th width=15>&nbsp;</th>');

    foreach my $id (sort keys %{$meters})
    {
        printf('<tr><td><a href="%s">%s</a></td>' . 
               '<td></td><td>%s</td><td></td>' . 
               '<td>%s</td><td></td><td>%s</td><td></td>%s</tr>',
               "admin.cgi?m=meter&sm=edit&id=$id",
               $meters->{$id}->{id},
               $meters->{$id}->{description},
               $meters->{$id}->{input},
               '<td><input type=checkbox name=delete value="' . $id . '"></td></tr>');
    }
    print '</table><br><input type=submit value="Delete Checked Records"><br><br>';
}


#////////////////////////////////////////////////////////////////////////////////////////
#// NAME: meter_form
#// DESC: Display the meter add / edit form.
#// HIST: 18jan2008  GJ ORIGINAL VERSION

sub meter_form
{
    my ($meterrecord, $submode) = @_;

    $submode = 'add' unless defined($submode);
    $meterrecord = $dbh->new_record('meters') unless defined($meterrecord);

    print <<EOF;
<h2>$submode Meter Settings</h2>
<p><a href="admin.cgi?m=meter&sm=list">Select Another Meter</a> (without
saving data).</p>
<form method=POST action=admin.cgi>
<input type=hidden name=m value=meter>
<input type=hidden name=sm value=add>
<input type=hidden name=id value="$meterrecord->{id}">
<table border=1 cellspacing=0 cellpadding=0>
<tr>
   <td class=fieldlabel>Description</td>
   <td><input type=text name=description size=30 value="$meterrecord->{description}"></td>
</tr>
<tr>
   <td class=fieldlabel>Units</td>
   <td><input type=text name=unit size=30 value="$meterrecord->{unit}"></td>
</tr>
<tr>
   <td class=fieldlabel>Conversion Factor</td>
   <td><input type=text name=cfac size=30 value="$meterrecord->{cfac}"></td>
</tr>
<tr valign=top>
   <td class=fieldlabel>Output Period (sec)</td>
   <td><input type=text name=output_period size=30 value="$meterrecord->{output_period}"></td>
</tr>
<tr>
   <td class=fieldlabel>IOCard</td>
   <td><input type=text name=iocard size=30 value="$meterrecord->{iocard}"></td>
</tr>
<tr>
   <td class=fieldlabel>Input No.</td>
   <td><input type=text name=input size=30 value="$meterrecord->{input}"></td>
</tr>
<tr>
   <td class=fieldlabel>Reading</td>
   <td><input type=text name=reading size=30 value="$meterrecord->{reading}"></td>
</tr>
</table>
<input type=submit value="\u$submode Meter"><BR>
EOF
}

####################################################################################
# NAME: meter_edit
# DESC: display a form containing the data associated with meter record number "id".
#        to allow it to be edited.
# HIST:
#       18mar2008  GJ  ORIGINAL VERSION
#
sub meter_edit
{
    print STDERR "meter_edit - id=",param('id'),"\n";
    my $meterrecord = $dbh->get_generic_single('meters',{'id' => param('id')});
    meter_form($meterrecord,'update');
}

####################################################################################
# NAME: meter_add
# DESC: add the data included as parameters to the database.
# HIST:
#       18mar2008  GJ  ORIGINAL VERSION
#
sub meter_add
{
    # Update the meter record in the database.
    my $meterrecord = $dbh->new_record('meters',{ 'id' => param('id'),
                                        'description' => param('description') || '',
                                        'unit' => param('unit') || '',
                                        'cfac' => param('cfac') || '',
                                        'output_period' => param('output_period') || '',
                                        'iocard' => param('iocard') || '',
                                        'input' => param('input') || '',
                                        'reading' => param('reading') || '',
                                                   });


    stop_daemon();
    if ($meterrecord->{id} == 0)
    {
        $meterrecord->{id} = $dbh->add_generic('meters',$meterrecord);
    }
    else
    {
        $dbh->update_generic_record('meters',
                                    { 'id' => $meterrecord->{'id'} }, 
                                    $meterrecord);
    }
    

    # Add a readings record to the database for this meter.
    my $readingrecord = $dbh->new_record('readings',{ 'id' => 'null',
                                        'meter' => $meterrecord->{'id'},
                                        'time' => '2008-04-12 00:00:00', #FIXME
					'reading' => $meterrecord->{'reading'},
                                        'rate' => '0',
                                                   });
    $readingrecord->{id} = $dbh->add_generic('readings',$readingrecord);

    start_daemon();


    meter_list();
}


####################################################################################
# NAME: user_delete
# DESC: delete the record number 'id'
# HIST:
#       14jan2008  GJ  ORIGINAL VERSION
#
# 
sub meter_delete
{
    foreach my $id (param('delete'))
    {
        $dbh->del_generic('meters',{id => $id});
    }
    meters_list();
}




##############################################################
# NAME: start_daemon
# DESC: start the metermon daemon by calling the metermonctrl binary
# HIST: 04may2008  GJ  ORIGINAL VERSION
#
sub start_daemon
{
    print("Starting Daemon.....\n");
    system("/usr/bin/metermonctrl start");
    sleep(1);
    admin_menu();
}

##############################################################
# NAME: stop_daemon
# DESC: stop the metermon daemon by calling the metermonctrl binary
# HIST: 04may2008  GJ  ORIGINAL VERSION
#
sub stop_daemon
{
    print("Stopping Daemon.....\n");
    system("/usr/bin/metermonctrl stop");
    sleep(5);
    admin_menu();
}



####################################################################################
# NAME: system_upgrade
# DESC: upgrade the meterserv system using the ipkg package manager.
# HIST:
#       29mar2008  GJ  ORIGINAL VERSION
#
# 
sub system_upgrade
{
    print("<h1>Upgrading system using ipkg</h1>");
    print("<p>");
    my @output = qx(/usr/bin/update_meterserv_package.sh) == 0
	or die("<p>oh no error calling update_meterserv_package.sh: $?</p>");
  
    foreach my $i (@output) {
	print("$i<br>");
    }
    print("</p>");
    print("<p>Done!</p>");
}

